<?php
namespace app\common\system\logic;

use app\common\BaseLogic;
use app\common\system\model\Department;
use app\common\system\model\UserDepartment;

class DepartmentLogic extends BaseLogic
{
    public function getDepartment($id, $fields="*") {
        $cacheName = "department:{$id}";

        if ($fields == "*") {
            $data = $this->redis->hGetAll($cacheName);
        } else {
            $data = $this->redis->hMGet($cacheName, $fields);
        }

        if (empty($data['id'])) {
            $model = new Department();
            $row = $model->where('id', $id)->find();
            if (!empty($row)) {
                $data = $row->getData();
                $this->redis->hMSet($cacheName, $data);
                if ($fields != "*") $data = array_search_keys($data, $fields);
            } else {
                $data = [];
            }
        }

        return $data;
    }

    // 获取所有子孙部门 id 数组 或者对象数组
    public function getChildren($id, $isArray=true) {
        $dpt = $this->getDepartment($id);
        if (empty($dpt)) return [];
        $path = $dpt['path'];

        $model = new Department();
        $rows = $model->where('path', 'like', "{$path}%")->select();

        return $isArray ? $rows->column('id') : $rows;
    }

    // 获取部门详情
    public function getDepartments($ids, $isArray=true) {
        if (empty($ids)) return [];

        $model = new \app\common\system\model\Department();
        $rows = $model->whereIn('id', $ids)->select();

        return $isArray ? $rows->toArray() : $rows;
    }

    // 获取部门（部门集合）下面的所有用户
    public function getDepartmentUsers($departmentIds, $onlyIds=true) {
        $where = [];
        if (is_array($departmentIds)) {
            $where[] = ['department_id', 'in', $departmentIds];
        } else {
            $where[] = ['department_id', '=', $departmentIds];
        }
        $model = new UserDepartment();
        $rows = $model->where($where)->select();

        if ($rows->isEmpty()) {
            return [];
        } else {
            return $onlyIds ? $rows->column('user_id') : $rows;
        }
    }

    // 用户的所有部门编号
    public function getUserDptIds($userId, $onlyIds=true)
    {
        $model = new \app\common\system\model\UserDepartment();
        $rows = $model->where('user_id', $userId)->select();

        return $onlyIds ? $rows->column('department_id') : $rows;
    }

    public function resetDptParentId(&$departmentsObj) {
        $departments = $departmentsObj->toArray();
        $ids = array_column($departments, 'id');
        foreach ($departments as &$row) {
            if (!in_array($row['parent_id'], $ids)) {
                $path = explode_filter_pop($row['path']);
                // 谁在前面，保留谁的顺序
                $cross = array_intersect($path, $ids);
                if (!empty($cross)) {
                    $row['parent_id'] = end($cross);
                } else {
                    $row['parent_id'] = 0;
                }
            }
        }

        return $departments;
    }

    // 添加用户部门
    public function createUserDepartment($userId, $operatorId, $ids)
    {
        $batchData = [];
        $data = [];
        $data['operator_id'] = $operatorId;
        $data['user_id'] = $userId;
        $data['create_time'] = time();
        foreach ($ids as $id) {
            $data['department_id'] = $id;
            array_push($batchData, $data);
        }
        $model = new UserDepartment();
        $result = $model->insertAll($batchData);

        return $result;
    }

    // 编辑用户部门
    public function updateUserDepartment($userId, $operatorId, $ids)
    {
        // 获取当前已有的
        $where = [];
        $where[] = ['user_id', '=', $userId];
        $model = new UserDepartment();
        $currentDepartments = $model->where($where)->select();
        $currentIds = $currentDepartments->column('department_id');
        $needDeleteIds = array_diff($currentIds, $ids);
        foreach ($currentDepartments as $row) {
            if (in_array($row->department_id, $needDeleteIds)) {
                $row->delete(true);
            }
        }

        $batchData = [];
        $data = [];
        $data['operator_id'] = $operatorId;
        $data['user_id'] = $userId;
        $data['create_time'] = time();
        $needAppendIds = array_diff($ids, $currentIds);
        foreach ($needAppendIds as $id) {
            $data['department_id'] = $id;
            array_push($batchData, $data);
        }
        $result = $model->insertAll($batchData);

        return $result;
    }
}